<template>
  <div class="resume-view-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>{{ resumeData.resume_name || '简历预览' }}</h2>
        <div class="resume-meta">
          <span class="meta-item">
            <el-icon><Calendar /></el-icon>
            创建时间：{{ formatDate(resumeData.created_at) }}
          </span>
          <span class="meta-item">
            <el-icon><Refresh /></el-icon>
            更新时间：{{ formatDate(resumeData.updated_at) }}
          </span>
          <span class="meta-item" v-if="resumeData.user_id">
            <el-icon><User /></el-icon>
            创建者：用户{{ resumeData.user_id }}
          </span>
        </div>
      </div>
      <div class="header-actions">
        <el-button @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </div>
    </div>

    <!-- 简历内容：完全复用ResumePreview -->
    <div class="resume-content">
      <el-row :gutter="24">
        <el-col :span="16">
          <ResumePreview :resume="resumeData" :template-style="templateStyle" :read-only="true" />
        </el-col>
        <el-col :span="8">
          <el-card class="info-card">
            <div class="info-title">简历信息</div>
            <div class="info-content">
              <div class="info-item">
                <label>简历名称：</label>
                <span>{{ resumeData.resume_name || '未命名简历' }}</span>
              </div>
              <div class="info-item">
                <label>使用模板：</label>
                <span>{{ templateName }}</span>
              </div>
              <div class="info-item">
                <label>创建时间：</label>
                <span>{{ formatDate(resumeData.created_at) }}</span>
              </div>
              <div class="info-item">
                <label>更新时间：</label>
                <span>{{ formatDate(resumeData.updated_at) }}</span>
              </div>
              <div class="info-item" v-if="resumeData.user_id">
                <label>创建者：</label>
                <span>用户{{ resumeData.user_id }}</span>
              </div>
              <div class="info-item">
                <label>简历状态：</label>
                <el-tag :type="getStatusType(resumeData.status)">
                  {{ getStatusText(resumeData.status) }}
                </el-tag>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Calendar, Refresh, User, ArrowLeft } from '@element-plus/icons-vue';
import axios from 'axios';
import ResumePreview from '@/components/ResumePreview.vue'

const route = useRoute();
const router = useRouter();

// 简历数据
const resumeData = ref({
  id: null,
  resume_name: '',
  basic_info: {},
  education_list: [],
  work_list: [],
  skills_list: '',
  template_id: null,
  template_name: '',
  created_at: null,
  updated_at: null,
  user_id: null,
  status: 1
});

// 模板样式（从选中的模板获取）
const templateStyle = ref({});
const templateName = ref('默认模板');

// 加载简历数据
const loadResumeData = async () => {
  try {
    const resumeId = route.params.id;
    if (!resumeId) {
      ElMessage.error('简历ID不存在');
      router.back();
      return;
    }

    const response = await axios.get(`http://localhost:7001/api/resumes/${resumeId}`);
    if (response.data.code === 0) {
      // 关键：如果有 dataValues，直接赋值为 dataValues 展开体
      const result = response.data.data;
      resumeData.value = result.dataValues ? result.dataValues : result;

      // 如果有模板ID，加载模板样式和名称
      if (resumeData.value.template_id) {
        await loadTemplateStyle(resumeData.value.template_id);
      } else {
        templateName.value = '默认模板';
      }
    } else {
      ElMessage.error(response.data.msg || '加载简历失败');
      router.back();
    }
  } catch (error) {
    console.error('加载简历失败:', error);
    ElMessage.error('加载简历失败，请重试');
    router.back();
  }
};

// 加载模板样式和名称
const loadTemplateStyle = async (templateId) => {
  try {
    const response = await axios.get(`http://localhost:7001/api/templates/${templateId}`);
    if (response.data.code === 0) {
      const templateData = response.data.data;
      templateStyle.value = templateData.template_data.style || {};
      templateName.value = templateData.name || '未知模板';
    }
  } catch (error) {
    console.error('加载模板样式失败:', error);
    templateName.value = '模板加载失败';
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 格式化日期范围
const formatDateRange = (startDate, endDate) => {
  const start = startDate ? new Date(startDate).toLocaleDateString('zh-CN') : '未知';
  const end = endDate ? new Date(endDate).toLocaleDateString('zh-CN') : '至今';
  return `${start} - ${end}`;
};

// 预览样式
const previewStyle = computed(() => ({
  fontFamily: templateStyle.value.base?.fontFamily || 'Microsoft YaHei, sans-serif',
  color: templateStyle.value.base?.primaryColor || '#2c3e50',
  backgroundColor: templateStyle.value.base?.bgColor || '#ffffff',
  padding: '20px',
  borderRadius: templateStyle.value.base?.borderRadius || '0px',
  minHeight: '600px'
}));

const nameStyle = computed(() => ({
  fontSize: (templateStyle.value.basic?.name?.fontSize || 24) + 'px',
  fontWeight: templateStyle.value.basic?.name?.fontWeight || 'bold',
  textAlign: templateStyle.value.basic?.name?.textAlign || 'left',
  margin: templateStyle.value.basic?.name?.margin || '0 0 10px 0',
  letterSpacing: templateStyle.value.basic?.name?.letterSpacing || 'normal',
  color: templateStyle.value.base?.primaryColor || '#2c3e50'
}));

const photoStyle = computed(() => ({
  width: (templateStyle.value.photo?.width || 100) + 'px',
  height: (templateStyle.value.photo?.height || 100) + 'px',
  border: templateStyle.value.photo?.border || '2px solid #ecf0f1',
  borderRadius: (templateStyle.value.photo?.borderRadius || 8) + 'px',
  overflow: 'hidden',
  flexShrink: 0,
  marginLeft: '20px'
}));

const basicInfoStyle = computed(() => ({
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'flex-start',
  marginBottom: '20px'
}));

const contactStyle = computed(() => ({
  fontSize: (templateStyle.value.base?.fontSize || 14) + 'px',
  color: templateStyle.value.base?.secondaryColor || '#7f8c8d',
  marginBottom: '10px'
}));

const introStyle = computed(() => ({
  fontSize: (templateStyle.value.base?.fontSize || 14) + 'px',
  lineHeight: templateStyle.value.base?.lineHeight || 1.6,
  color: templateStyle.value.base?.secondaryColor || '#7f8c8d'
}));

const titleStyle = computed(() => ({
  fontSize: (templateStyle.value.education?.title?.fontSize || 16) + 'px',
  fontWeight: templateStyle.value.education?.title?.fontWeight || 600,
  color: templateStyle.value.education?.title?.color || templateStyle.value.base?.primaryColor || '#2c3e50',
  margin: '20px 0 12px 0',
  paddingBottom: '4px',
  borderBottom: templateStyle.value.education?.title?.borderBottom || '2px solid #ecf0f1'
}));

const itemStyle = computed(() => ({
  marginBottom: '14px',
  padding: '12px 15px',
  backgroundColor: '#ffffff',
  borderRadius: (templateStyle.value.education?.item?.borderRadius || 8) + 'px',
  boxShadow: templateStyle.value.education?.item?.boxShadow || '0 2px 6px rgba(0,0,0,0.05)'
}));

const itemMainStyle = computed(() => ({
  fontWeight: 500,
  color: templateStyle.value.base?.primaryColor || '#2c3e50',
  fontSize: (templateStyle.value.base?.fontSize || 14) + 'px'
}));

const itemDateStyle = computed(() => ({
  fontSize: ((templateStyle.value.base?.fontSize || 14) - 1) + 'px',
  color: templateStyle.value.base?.secondaryColor || '#7f8c8d'
}));

const itemDescStyle = computed(() => ({
  fontSize: ((templateStyle.value.base?.fontSize || 14) - 1) + 'px',
  lineHeight: templateStyle.value.base?.lineHeight || 1.6,
  marginTop: '6px',
  color: templateStyle.value.base?.secondaryColor || '#7f8c8d'
}));

const skillsStyle = computed(() => ({
  fontSize: (templateStyle.value.base?.fontSize || 14) + 'px',
  lineHeight: templateStyle.value.base?.lineHeight || 1.6,
  color: templateStyle.value.base?.secondaryColor || '#7f8c8d'
}));

// 操作函数
const handleBack = () => {
  router.back();
};

// 状态处理函数
const getStatusType = (status) => {
  switch (status) {
    case 1: return 'warning'; // 草稿
    case 2: return 'success'; // 完成
    case 3: return 'primary'; // 已发布
    default: return 'info';
  }
};

const getStatusText = (status) => {
  switch (status) {
    case 1: return '草稿';
    case 2: return '完成';
    case 3: return '已发布';
    default: return '未知';
  }
};

// 页面加载时获取数据
onMounted(() => {
  loadResumeData();
});
</script>

<style scoped>
.resume-view-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #fff;
  font-size: 24px;
  font-weight: 600;
}

.resume-meta {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.resume-content {
  max-width: 1400px;
  margin: 0 auto;
}

.preview-card,
.info-card {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 20px;
}

.preview-title,
.info-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 2px solid #eee;
}

.preview-content {
  border-radius: 8px;
}

.preview-section {
  margin-bottom: 20px;
}

.name-photo {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
}

.resume-name {
  margin: 0 0 10px 0;
  flex: 1;
}

.photo-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.contact-info p {
  margin: 4px 0;
}

.intro-text {
  margin: 10px 0;
}

.section-title {
  margin: 20px 0 12px 0;
}

.preview-item {
  margin-bottom: 14px;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-desc {
  margin: 6px 0 0 0;
}

.skills-text {
  margin: 0;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
}

.info-item span {
  color: #333;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 20px;
  }
  
  .resume-meta {
    justify-content: center;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
  }
}
</style>
